// pages/schedule/schedule.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var dateTimePicker = require('../../utils/dateTimePicker.js');
var qqmapsdk = new QQMapWX({
  key: 'Y43BZ-DXOE6-KTZSL-MV7HR-HMUYO-CBFBH' //这里自己的key秘钥进行填充
});;
const api = require("../../libs/api")
const app = getApp();

import {
  formatDate
} from '../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timslit:'',
    a: 1,
    isup: false,
    isRemove: false, //是否删除成功
    islogin: false, //登录状态
    schedule: [], //日程、未完成事件
    finish: [], //完成事件
    cit: '',
    now: '',
    bh: "",
    weatherData: '',
    currentTab: 0, //导航栏ID,用于确定选择状态和页面的切换
    winHeight: 0,
    winWidth: 0,
    t: '',
    b: '',
    f: '',
    tit: '',
    //下拉时间选项初始化
    startYear: 2019,
    endYear: 2090,
    startDateArray:null,
    endDateArray:null,
    startTime:null,
    endTime:null
  },


  /**********  跳转  ******** */
  //跳转日历
  rili: function (e) {
    wx.navigateTo({
      url: '../calender/calender',
    })
  },
  //跳转
  gotoresult: function (e) {
    wx.navigateTo({
      url: '../weather/weather',
    })
  },
  //登录
  gotoLogin: function (e) {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  //文章跳转
  firstText: function (e) {
    wx.navigateTo({
      url: '../other/firstText/firstText',
    })
  },
  secandText: function (e) {
    wx.navigateTo({
      url: '../other/secondText/secondText',
    })
  },
  thirdText: function (e) {
    wx.navigateTo({
      url: '../other/thirdText/thirdText',
    })
  },

  //纪念日跳转
  anniversary(){
    setTimeout(function () {

      wx.hideLoading()
      app.msg('你去看看隔壁有没有实现')

    }, 2000)
   
  },

  //报表跳转
  reckoning(){
    setTimeout(function () {

      wx.hideLoading()
      app.msg('作者很懒，试着去点击一下轮播图吧')

    }, 2000)
    
  },
  //////////////////////////////////



  /******swiper 区*********** */
  //滑动切换   
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  //点击切换  
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  //变化
  swiperchange: function (e) {
    var that = this
    console.log(e.detail.current)
    that.setData({
      'currentTab': e.detail.current
    })
  },
  ///////////////////////////////////////////



  /** 生命周期函数--监听页面加载  *****/
  onLoad: function (options) {

    var that = this;
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // var startDate = this.formatDate(new Date());
    that.setData({
      startDate: obj.dateTime,
      startDateArray: obj.dateTimeArray,
      endDate: obj.dateTime,
      endDateArray: obj.dateTimeArray
    })
    that.Timechange()
    if (app.getLoginStatus()) {
      wx.showLoading({
        title: '加载中',
      })
      setTimeout(function () {
        wx.hideLoading()
        let userinfo = wx.getStorageSync('userinfo');
        that.setData({
          islogin: true,
        })
      }, 500)
    } else {
      console.log("tttt")
      that.setData({
        islogin: false,
      })
    }

    // this.onShow();

  },



  onShow: function () {

    var that = this;
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    // console.log("当前时间戳为：" + timestamp);
    //获取当前时间
    var n = timestamp * 1000;
    var date = new Date(n);
    //获取时间段
    var h = date.getHours();
    if (0 < h && h <= 6) {
      that.setData({
        bh: '凌晨好！'
      })
    } else if (6 <= h && h < 11) {
      that.setData({
        bh: '早上好！'
      })
    } else if (11 <= h && h <= 13) {
      that.setData({
        bh: '中午好！'
      })
    } else if (13 <= h && h <= 16) {
      that.setData({
        bh: '下午好！'
      })
    } else if (16 <= h && h <= 18) {
      that.setData({
        bh: '傍晚好！'
      })
    } else {
      that.setData({
        bh: '晚上好！'
      })

    }



    //显示日期
    var DATE = formatDate(new Date());
    that.setData({
      date: DATE,
    });
    //获取系统信息
    var query = wx.createSelectorQuery();
    query.select('.top').boundingClientRect(
      function (rect) {
        that.setData({
          h: rect.height
        })
      }).exec();
    query.select('.banner').boundingClientRect(
      function (rect) {
        that.setData({
          b: rect.height
        })
      }).exec();
    query.select('.function').boundingClientRect(
      function (rect) {
        that.setData({
          f: rect.height
        })
      }).exec();
    query.select('.tit').boundingClientRect(
      function (rect) {
        that.setData({
          tit: rect.height
        })
      }).exec();

    //获取可视化高度
    wx.getSystemInfo({
      success: (res) => {
        let clientWidth = res.windowWidth;
        let ratio = 750 / clientWidth;
        that.setData({
          winHeight: res.windowHeight * ratio,
          winWidth: ratio,
          clientHeight: res.windowHeight,
        });
      }
    })
    let vm = this;
    vm.onLoad();
    vm.getUserLocation();
    vm.getscheduleList();
  },

  openChese() {
    this.setData({
      isup: true
    })
  },


  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        //console.log(JSON.stringify(res))

        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        } else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {

        // console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        wx.setStorageSync('city', city)
        wx.setStorageSync('district', district)
        vm.setData({
          province: province,
          cit: city,
          district: district,
          latitude: latitude,
          longitude: longitude
        });
        var descCity = city.substring(0, city.length - 1);
        vm.getWeather(descCity);
        console.log("你好" + descCity);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        //console.log(res);
      }


    })
  },
  //获取天气信息
  getWeather: function (city) {

    var that = this; //this不可以之间在微信API函数内部使用，把this赋值到that里面
    var params = {
      location: city,
      key: 'c2de3a05d76e44d69d15a55fb3f9a18c'
    }
    wx.request({

      url: 'https://free-api.heweather.net/s6/weather/now?', //主要url
      data: params,

      success: function (res) { //如果天气获取函数运行成功，把获取到的结果放入到res对象当中
        console.log(res.data),
          wx.setStorageSync('tmp', res.data.HeWeather6[0].now),

          that.setData({
            now: res.data.HeWeather6[0].now //调用res当中的实时天气数据
          })
      }
    })


  },
  //下拉刷新
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '加载中',
    })

    setTimeout(function () {

      wx.hideLoading()
      app.msg('加载成功')

    }, 2000)


  },


  //去详情页面
  toDetails(event) {
    let {
      id
    } = event.currentTarget.dataset;
    // console.log(event.currentTarget.dataset)
    wx.navigateTo({
      url: `/pages/noteDetails/noteDetails?id=${id}`
    })
  },


  //滑动事件处理
  touchmove: function (e) {
    let a = this.data.a
    a++
    var that = this,
    index = e.currentTarget.dataset.index; //当前索引、
    switch(this.data.currentTab){
    case 0:that.data.schedule.forEach(function (v, i) {
      v.isTouchMove = false
      if (i == index) {
        if (a % 2 == 0) { //右滑
          v.isTouchMove = true
          that.setData({
            a
          })
          console.log("你点击了")
        } else { //左滑
          v.isTouchMove = false
          that.setData({
            a
          })
        }
        console.log("你mei点击了")
      }
      });break;
      case 1:that.data.finish.forEach(function (v, i) {
        v.isTouchMove = false
        if (i == index) {
          if (a % 2 == 0) { //右滑
            v.isTouchMove = true
            that.setData({
              a
            })
            console.log("你点击了")
          } else { //左滑
            v.isTouchMove = false
            that.setData({
              a
            })
          }
          console.log("你mei点击了")
        }
        });break;
  };
    //更新数据
    that.setData({
      schedule: that.data.schedule,
      finish:that.data.finish
    })
  
  },


  //获取待办与完成事件
  getscheduleList() {
    //拿到data里面的数据id,按这个来查询
    let openid = wx.getStorageSync('openid');
    let stateid = "e62469b25fc241db008200c3013dcb25"; //完成
    let stateid1 = "2a7b532a5fc24202007e446670b02cc7"; //未完成
    let where = {
      _openid: openid,
      stateid: stateid1
    }; //查询条件
    let targetType = "rank"; //排序条件

    //获取待办事件
    api.find('notepads', where, 0, 10, targetType, 'asc').then(res => {
      console.log(res.data)
      this.setData({
        schedule: res.data
      })
      wx.hideLoading({})
    })
    //获取完成事件
    api.find('notepads', where = {
      _openid: openid,
      stateid: stateid
    }, 0, 100000, targetType).then(res => {
      console.log(res.data)
      this.setData({
        finish: res.data
      })
      wx.hideLoading({})
    })
  },

  //时间滚动选项

  bindStartDateChange(e) {
    console.log(e.detail)
    this.setData({
      startDate: e.detail.value,
    })
    this.Timechange();
    // this.shouquan(e.currentTarget.dataset)
    console.log(e.currentTarget.dataset)
    let _id = e.currentTarget.dataset.id;
    let state = e.currentTarget.dataset.state;
        if (true) {
          console.log(this.data.timslit)
          wx.showLoading({
            title: '正在修改',
          })
          if (!state) {
            api.callfun("updata", {
              where: { _id: _id },
              data: {
                state: true,
                stateid: 'e62469b25fc241db008200c3013dcb25',
                reminde: this.data.timslit
              },
              collectionName: "notepads"
            }).then(res => {
              wx.hideLoading()
              wx.showToast({
                title: '修改成功',
              })
              this.getmenuDetaile();
            }).catch(err => {
              wx.showToast({
                title: '修改失败',
              })
            })
          } else {
            api.callfun("updata", {
              where: { _id: _id },
              data: {
                state: false,
                stateid: '2a7b532a5fc24202007e446670b02cc7',
                reminde: this.data.timslit
              },
              collectionName: "notepads"
            }).then(res => {
              wx.hideLoading()
              wx.showToast({
                title: '修改成功',
              })
              this.getscheduleList();
            }).catch(err => {
              wx.showToast({
                title: '修改失败',
              })
            })
      
          }
        }
    
  },
  //获取设置的时间
  Timechange() {
    let startDateArray = this.data.startDateArray;
    let startDate = this.data.startDate;
    let timslit = startDateArray[0][startDate[0]] + '-' + startDateArray[1][startDate[1]] + '-' + startDateArray[2][startDate[2]] + ' ' + startDateArray[3][startDate[3]] + ':' + startDateArray[4][startDate[4]]
    this.setData({
      timslit: timslit
    })
  },
  //修改状态
  finish(e){

    let _id = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '正在修改',
    })
    
    api.callfun("updata",{
     where:{_id:_id},
     data:{
      //  html:html,
      //  center: center,
      //  notepadPic: '',
      //  notepadTypeid: id,
      //  title: name,
      //  uptime: DATE,
      //  rank: gtetime
      state : true,
      stateid:'e62469b25fc241db008200c3013dcb25'
     },
     collectionName:"notepads"
   }).then(res => {
    wx.hideLoading()
    wx.showToast({
      title: '修改成功',
    })
    setTimeout(() => {
      wx.hideLoading()
      this.getscheduleList();
    }, 1000)
  })

  console.log(e.currentTarget.dataset)
  },

  //删除事件
  removenotepad: function (e) {
    let {
      id
    } = e.currentTarget.dataset;
    let openid = wx.getStorageSync('openid');
    api.callfun("remove", {
      collectionName: "notepads",
      where: {
        _id: id,
        _openid: openid
      }
    }).then(res => {
      this.setData({
        isRemove: true
      })
      wx.showToast({
        title: '删除成功',
      })
      this.getscheduleList();
    })
    console.log("你点了删除")
  },










  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


})